package m4;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Scanner;

public class Consumer {
    public static void main(String[] args) throws Exception {
        // 连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");  // wht6.cn
        // f.setPort(5672); //默认端口可以不设置
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c = f.newConnection().createChannel();

        //1.定义独占的随机队列  2.定义交换机  3.用绑定键绑定
        //由服务器随机命名, false,true,true -- 非持久、独占、自动删除
        String queue = c.queueDeclare().getQueue();
        c.exchangeDeclare("direct_logs", BuiltinExchangeType.DIRECT);
        System.out.println("输入绑定键，用空格隔开：");
        String s = new Scanner(System.in).nextLine();
        String[] a = s.split("\\s+"); // ["aaa",  "bbb",  "ccc"]
        for (String key:a) {
            c.queueBind(queue, "direct_logs", key);
        }

        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String msg = new String(message.getBody());
                String key = message.getEnvelope().getRoutingKey();
                System.out.println(key+" - "+msg);
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {
            }
        };
        // 从随机队列 queue 接收消息
        c.basicConsume(queue,true, deliverCallback, cancelCallback);

    }
}
